#!/bin/bash
# description:　Tomcat Auto Install Server
# version:	1.0
# author:	zhangyanbin
# contact:	yanbin_zhang@foxitsoftware.com
#	
IsYUMClean=0
# Add Maven repo
sudo yum install -y wget
if [ ! -e /etc/yum.repos.d/epel-apache-maven.repo ]; then
	echo "Installing Apache Maven repo..."
	sudo wget -q http://repos.fedorapeople.org/repos/dchen/apache-maven/epel-apache-maven.repo -O /etc/yum.repos.d/epel-apache-maven.repo
	IsYUMClean=1
fi

#Add zookeeper repo
if [ ! -e /etc/yum.repos.d/cloudera.repo ]; then
	cp /vagrant/vagrant/repo/cloudera.repo  /etc/yum.repos.d
fi

echo "Install Mongodb....."
#Install Mongodb (and any needed extensions).
if [ ! -e /etc/yum.repos.d/CentOS-Mongodb**.repo ]; then
	echo "Installing Mongodb repo..."
	
	if [ "`getconf LONG_BIT`" = "32" ];then
		cp /vagrant/vagrant/repo/CentOS-Mongodb32.repo /etc/yum.repos.d
	else 
		cp /vagrant/vagrant/repo/CentOS-Mongodb64.repo /etc/yum.repos.d
	fi
	IsYUMClean=1
fi

if [ $IsYUMClean -eq 1 ]
then
	sudo yum clean all
	if [ $? -ne 0 ]; then
	   echo "Yum clean all failure[Error]"
	   exit 1
	else
	  echo "Yum clean all success[OK]"
	fi
fi

# Install Tomcat and Maven (and any needed extensions).-server mongodb-org-mongos mongodb-org-shell
pkgs=( mod_ssl java-1.7.0-openjdk-devel tomcat apache-maven mongodb-org-server mongodb-org-mongos mongodb-org-shell hadoop-zookeeper-server )
for i in "${pkgs[@]}"
do
    if rpm -qa | grep -q ^$i; then
        echo "$i already installed"
    else
        echo "Installing $i and dependencies..."
        sudo yum install -y $i
		if [ $? -ne 0 ]
		then
			echo "yum install -y $i.......[ERROR]"
			exit 1;
		fi
    fi
done

#Stop iptables 
sudo chkconfig iptables off
service iptables stop

#Make sure zookeeper is set to start on startup and is running
sudo chkconfig hadoop-zookeeper-server on
sudo service hadoop-zookeeper-server restart

# Make sure Mongodb is set to start on startup shuut on shutdown and is running
sudo chkconfig mongod on
sudo service mongod restart
#Make sure Mongodb is stoped when os shutdown
if [ ! -e "/etc/rc.d/rc0.d/K01mongod" ]; then
	ln -s /etc/rc.d/init.d/mongod /etc/rc.d/rc0.d/K01mongod
fi

# Make sure Tomcat is set to start on startup
TOMCAT_HOME=/usr/share/tomcat
sudo chkconfig tomcat on
if [ ! -e "/usr/share/tomcat/foxit-log" ]; then
	mkdir $TOMCAT_HOME/foxit-log
	chown -Rf tomcat.tomcat $TOMCAT_HOME/foxit-log
fi
usermod -a -G root tomcat
#Set tomcat catalina options,invoid pergem space error
POSITION="#!\/bin\/bash"
TOMCAT_OPTS="CATALINA_OPTS=\"-server -Xms512m -Xmx800m -XX:MaxPermSize=512m\""
sed -i "/CATALINA_OPTS=/d" /usr/sbin/tomcat
sed -i "/$POSITION/a $TOMCAT_OPTS" /usr/sbin/tomcat

#Init mongodb collections and User Credentials
sudo chmod 0755 /vagrant/vagrant/mongoinit.sh
sudo /vagrant/vagrant/mongoinit.sh